<template>
    <div>
        <v-table :height="200" v-if="logs.length !== 0">
            <template v-slot:default>
                <tbody>
                <tr v-for="(item, index) in logs" v-bind:key="index">
                    <td>{{ item.message }}</td>
                    <td width="220px" style="text-align: right;">{{ new Date(item.time * 1000).toLocaleString() }}</td>
                </tr>
                </tbody>
            </template>
        </v-table>
        <div style="height: 200px;" v-else>
            {{$t('log.no_data')}}
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import api from '@/utils/api.js'

const logs = []
let stream = null
        
onMounted(() => {
            getStream()
        })

onUnmounted(() => {
            console.log(1111)
            stream.close()
        })


function getStream() {
                stream = new EventSource(api.baseURL + '/livelog')
                stream.onmessage = (event) => {
                    let data = JSON.parse(event.data)
                    switch (data['Type']) {
                        case 'submit_flag':
                            push({
                                time: data['Time'],
                                message: $t('log.submit_flag', {
                                    'from': data['Message']['From'],
                                    'to': data['Message']['To'],
                                    'challenge': data['Message']['Challenge'],
                                })
                            })
                            break;
                        case 'check_down':
                            push({
                                time: data['Time'],
                                message: $t('log.check_down', {
                                    'team': data['Message']['Team'],
                                    'challenge': data['Message']['Challenge'],
                                })
                            })
                            break;
                    }
                };
                stream.onerror = function (err) {
                    console.log(err)
                };
            }
function push(data) {
                if (logs.length > 30) {
                    logs = logs.slice(0, 30)
                }
                logs.unshift(data)
            }
</script>

<style scoped>

</style>